<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
    :disabled="disabled"
  >
    <el-table :data="formData" show-summary :summary-method="getSummaries" class="-mt-10px">
      <el-table-column label="序号" type="index" align="center" width="60" />
      <el-table-column label="执行顺序" min-width="180">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.sort`" :rules="formRules.sort" class="mb-0px!">
            <el-input-number
              v-model="row.sort"
              controls-position="right"
              :min="1"
              :precision="2"
              class="!w-100%"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="工序名称" min-width="100">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.name`" :rules="formRules.name" class="mb-0px!">
            <el-input v-model="row.name" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="负责人员" min-width="100">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.userId`" :rules="formRules.userId" class="mb-0px!">
            <cascader-user v-model="row.userId" />
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="计费方式" min-width="100">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.type`" :rules="formRules.type" class="mb-0px!">
            <el-select v-model="row.type" placeholder="请选择计费方式">
              <el-option label="计时" value="计时" />
              <el-option label="计件" value="计时" />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>


      <el-table-column label="标准耗时(小时)" min-width="120">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.elapsedTime`" class="mb-0px!">
            <el-input-number
              v-model="row.elapsedTime"
              controls-position="right"
              :min="0.01"
              :precision="2"
              :step="0.1"
              class="!w-100%"
            />
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="加工单价" min-width="120">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.price`" class="mb-0px!">
            <el-input-number
              v-model="row.price"
              controls-position="right"
              :min="0.01"
              :precision="2"
              class="!w-100%"
            />
          </el-form-item>
        </template>
      </el-table-column>



      <el-table-column label="所需费用" prop="allPrice" min-width="100">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.allPrice`" class="mb-0px!">
            <el-input disabled v-model="row.allPrice" :formatter="erpPriceInputFormatter" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="计划完工时间" prop="planFinishTime" min-width="100">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.planFinishTime`" class="mb-0px!">
            <el-date-picker
              v-model="row.planFinishTime"
              type="date"
              placeholder="选择计划完工时间"
              value-format="x"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.remark`" class="mb-0px!">
            <el-input v-model="row.remark" placeholder="请输入备注" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link>—</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3" v-if="!disabled">
    <el-button @click="handleAdd" round>+ 添加工序流程</el-button>
  </el-row>
</template>
<script setup lang="ts">
import { ProductVO } from '@/api/erp/product/product'
import {
  erpCountInputFormatter,
  erpPriceInputFormatter,
  erpPriceMultiply,
  getSumValue
} from '@/utils'

defineOptions({ name: 'ProducePlanProcessItemForm' })
const props = defineProps<{
  items?: any[]
  disabled: false
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  sort: [{ required: true, message: '执行顺序不能为空', trigger: 'blur' }],
  count: [{ required: true, message: '产品数量不能为空', trigger: 'blur' }]
})
const formRef = ref([]) // 表单 Ref
const productList = ref<ProductVO[]>([]) // 产品列表

/** 初始化设置出库项 */
watch(
  () => props.items,
  async (val) => {
    formData.value = val ?? []
    console.log('formData.value', formData.value)
  },
  { immediate: true }
)

/** 监听合同产品变化，计算合同产品总价 */
watch(
  () => formData.value,
  (val) => {
    if (!val || val.length === 0) {
      return
    }
    // 循环处理
    val.forEach((item) => {
      item.allPrice = erpPriceMultiply(item.price, item.count)
    })
  },
  { deep: true }
)

/** 合计 */
const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column, index: number) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (['count', 'allPrice'].includes(column.property)) {
      const sum = getSumValue(data.map((item) => Number(item[column.property])))
      sums[index] =
        column.property === 'count' ? erpCountInputFormatter(sum) : erpPriceInputFormatter(sum)
    } else {
      sums[index] = ''
    }
  })

  return sums
}

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    count: 1
  }
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index: number) => {
  formData.value.splice(index, 1)
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}
defineExpose({ validate })

/** 初始化 */
onMounted(async () => {
  // 默认添加一个
  if (formData.value.length === 0) {
    handleAdd()
  }
})
</script>
